<template>
  <n-config-provider :theme="darkTheme">
    <div class="dashboard">
      <!-- 头部区域 -->
      <n-card class="header-card" :bordered="false">
        <div class="header-content">
          <div class="header-left">
            <n-gradient-text :size="24" type="primary">{{ currentTime }}</n-gradient-text>
          </div>
          <div class="header-center">
            <n-gradient-text :size="36" type="info">股票交易实时监控平台</n-gradient-text>
          </div>
          <div class="header-right">
            <n-space>
              <n-statistic label="今日总交易" :value="totalTradeVolume" :precision="0">
                <template #suffix>笔</template>
              </n-statistic>
            </n-space>
          </div>
        </div>
      </n-card>

      <div class="content-wrapper">
        <!-- 左侧面板 -->
        <div class="side-panel">
          <n-card v-for="(stats, title, index) in statsPanels" 
                 :key="index"
                 :class="['info-card', `panel-${index + 1}`]"
                 :bordered="false">
            <template #header>
              <n-space align="center">
                <n-icon size="20">
                  <component :is="getPanelIcon(index)" />
                </n-icon>
                <span>{{ title }}</span>
              </n-space>
            </template>
            <n-list>
              <n-list-item v-for="(value, label) in stats" :key="label">
                <n-space justify="space-between" align="center">
                  <span class="label">{{ label }}：</span>
                  <n-statistic :value="value" :precision="2" class="value-statistic">
                    <template #suffix>
                      {{ label.includes('额') ? '元' : '笔' }}
                    </template>
                  </n-statistic>
                </n-space>
              </n-list-item>
            </n-list>
          </n-card>
        </div>

        <!-- 中间区域 -->
        <div class="center-panel">
          <n-card title="交易地域分布" :bordered="false" class="map-container">
            <template #header>
              <n-space align="center">
                <n-icon size="20">
                  <MapOutline />
                </n-icon>
                <span>交易地域分布</span>
              </n-space>
            </template>
            <div ref="map" class="map-content"></div>
          </n-card>

          <div class="bottom-charts">
            <n-card v-for="(ranking, index) in rankings" 
                   :key="index"
                   :class="['chart-item', `ranking-${index + 1}`]"
                   :bordered="false">
              <template #header>
                <n-space align="center">
                  <n-icon size="20">
                    <component :is="getRankingIcon(index)" />
                  </n-icon>
                  <span>{{ ranking.title }}</span>
                </n-space>
              </template>
              <n-list hoverable clickable class="ranking-list">
                <n-list-item v-for="(item, idx) in ranking.data" 
                            :key="idx"
                            class="ranking-item">
                  <n-space align="center">
                    <n-tag :type="getTagType(idx)" round class="rank-tag">
                      {{ idx + 1 }}
                    </n-tag>
                    <span class="name">{{ item.name }}</span>
                    <n-statistic :value="item.value" :precision="2" class="value-statistic">
                      <template #suffix>元</template>
                    </n-statistic>
                  </n-space>
                </n-list-item>
              </n-list>
            </n-card>
          </div>
        </div>

        <!-- 右侧面板 -->
        <div class="side-panel">
          <n-card title="交易额趋势" :bordered="false" class="info-card">
            <template #header>
              <n-space align="center">
                <n-icon size="20">
                  <TrendingUpOutline />
                </n-icon>
                <span>交易额趋势</span>
              </n-space>
            </template>
            <v-chart :option="tradeChartOption" autoresize />
          </n-card>

          <n-card title="交易量统计" :bordered="false" class="info-card">
            <template #header>
              <n-space align="center">
                <n-icon size="20">
                  <StatsChartOutline />
                </n-icon>
                <span>交易量统计</span>
              </n-space>
            </template>
            <n-space vertical align="center" justify="center" class="volume-stats">
              <n-statistic :value="totalTradeVolume" :precision="0" class="total-volume">
                <template #prefix>
                  <n-icon size="24">
                    <SwapVerticalOutline />
                  </n-icon>
                </template>
                <template #suffix>笔</template>
              </n-statistic>
              <n-progress type="circle" 
                         :percentage="getTradeProgress()" 
                         :color="progressColor"
                         :rail-color="progressRailColor"
                         :stroke-width="10"
                         class="progress-circle" />
            </n-space>
          </n-card>
        </div>
      </div>
    </div>
  </n-config-provider>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import axios from 'axios';
import chinaJson from '@/assets/china.json';
import * as echarts from 'echarts';
import { darkTheme } from 'naive-ui';
import { useThrottleFn } from '@vueuse/core';
import {
  TimeOutline,
  StatsChartOutline,
  TrendingUpOutline,
  MapOutline,
  SwapVerticalOutline,
  PodiumOutline,
  BusinessOutline
} from '@vicons/ionicons5'

// 状态定义
const number = ref(0);
const currentTime = ref('');
const processingSpeed = ref(0); // 新增处理速度状态
const stats = ref({
  totalBuyAmount: 0,
  totalSellAmount: 0,
  totalBuyVolumeCount: 0,
  totalSellVolumeCount: 0,
  totalBuyAmount_minute: 0,
  totalSellAmount_minute: 0,
  totalBuyVolumeCount_minute: 0,
  totalSellVolumeCount_minute: 0,
  totalBuyAmount_hour: 0,
  totalSellAmount_hour: 0,
  totalBuyVolumeCount_hour: 0,
  totalSellVolumeCount_hour: 0
});
const sellAndBuyList = ref([]);
const topPlatforms = ref([]);
const topPlaces = ref([]);
const totalTradeVolume = ref(0); // 新增总交易量状态
const topstock = ref([]);
const map = ref(null); // 创建一个 ref 来引用 map 元素
const speed  = ref(0);
// 数据格式化函数
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 新增计算属性
const statsPanels = computed(() => ({
  '实时交易统计(每秒)': {
    '总购入额': stats.value.totalBuyAmount,
    '总出售额': stats.value.totalSellAmount,
    '买入订单': stats.value.totalBuyVolumeCount,
    '卖出订单': stats.value.totalSellVolumeCount,
    '处理速度': speed.value
  },
  '实时交易统计(每分钟)': {
    '总购入额': stats.value.totalBuyAmount_minute,
    '总出售额': stats.value.totalSellAmount_minute,
    '买入订单': stats.value.totalBuyVolumeCount_minute,
    '卖出订单': stats.value.totalSellVolumeCount_minute
  },
  '实时交易统计(每小时)': {
    '总购入额': stats.value.totalBuyAmount_hour,
    '总出售额': stats.value.totalSellAmount_hour,
    '买入订单': stats.value.totalBuyVolumeCount_hour,
    '卖出订单': stats.value.totalSellVolumeCount_hour
  }
}));

const rankings = computed(() => ([
  {
    title: '交易平台TOP10',
    data: (topPlatforms.value || []).map(item => {
      const [name, value] = item.split(':');
      return { name, value: Number(value) };
    })
  },
  {
    title: '交易股票类型TOP10',
    data: (topstock.value || []).map(item => {
      const [name, value] = item.split(':');
      return { name, value: Number(value) };
    })
  }
]));

// 优化的数据获取函数
const fetchData = useThrottleFn(async () => {
  try {
    const [
      speedRes,
      statsRes,
      sellAndBuyRes,
      platformsRes,
      placesRes,
      stockName
    ] = await Promise.all([
      axios.get('/api/stock/processing_speed', { params: { number: number.value } }),
      axios.get('/api/stock/tradeAndBuy', { params: { number: number.value } }),
      axios.get('/api/stock/tradeVolume', { params: { number: number.value } }),
      axios.get('/api/stock/tradeTenPlatform'),
      axios.get('/api/stock/tradeTenPlace'),
      axios.get('/api/stock/tradeTenStock')
    ]);

    // 添加数据验证
    if (Array.isArray(speedRes.data)) processingSpeed.value = parseFloat(speedRes.data[0]);
    if (Array.isArray(statsRes.data)) {
      stats.value = {
        totalBuyAmount: statsRes.data[0] || 0,
        totalSellAmount: statsRes.data[1] || 0,
        totalBuyVolumeCount: statsRes.data[2] || 0,
        totalSellVolumeCount: statsRes.data[3] || 0,
        totalBuyAmount_minute: statsRes.data[4] || 0,
        totalSellAmount_minute: statsRes.data[5] || 0,
        totalBuyVolumeCount_minute: statsRes.data[6] || 0,
        totalSellVolumeCount_minute: statsRes.data[7] || 0,
        totalBuyAmount_hour: statsRes.data[8] || 0,
        totalSellAmount_hour: statsRes.data[9] || 0,
        totalBuyVolumeCount_hour: statsRes.data[10] || 0,
        totalSellVolumeCount_hour: statsRes.data[11] || 0
      };
    }

    // 确保数据是数组
    sellAndBuyList.value = Array.isArray(sellAndBuyRes.data) ? sellAndBuyRes.data : [];
    topPlatforms.value = Array.isArray(platformsRes.data) ? platformsRes.data : [];
    topPlaces.value = Array.isArray(placesRes.data) ? placesRes.data : [];
    topstock.value = Array.isArray(stockName.data) ? stockName.data : [];

    // 计算总交易量
    totalTradeVolume.value = (stats.value.totalBuyVolumeCount_hour || 0) + 
                            (stats.value.totalSellVolumeCount_hour || 0);
    speed.value = (stats.value.totalBuyVolumeCount || 0) + 
                 (stats.value.totalSellVolumeCount || 0);
    number.value++;
    // 初始化地图
    initMap();
  } catch (error) {
    console.error('数据获取失败:', error);
  }
}, 1000);

// 更新时间
const updateTime = () => {
  currentTime.value = new Date().toLocaleString();
};

// 生命周期钩子
onMounted(() => {
  fetchData();
  updateTime();

  const dataTimer = setInterval(fetchData, 1000);
  const timeTimer = setInterval(updateTime, 1000);

  onUnmounted(() => {
    clearInterval(dataTimer);
    clearInterval(timeTimer);
  });
});

// 地图初始化函数
function initMap() {
  if (!map.value) {
    console.error('Map element is not found');
    return;
  }

  const chart = echarts.init(map.value);
  const mapData = (topPlaces.value || []).map(item => {
    const [province, value] = item.split(':');
    return { name: province, value: parseInt(value, 10) || 0 };
  });

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}',
    },
    visualMap: {
      min: 0,
      max: Math.max(...mapData.map(item => item.value), 0),
      inRange: {
        color: ['#e0ffff', '#006edd'],
      },
    },
    series: [
      {
        name: '中国地图',
        type: 'map',
        mapType: 'china',
        roam: false,
        data: mapData,
      },
    ],
  };

  if (chinaJson) {
    echarts.registerMap('china', chinaJson);
    chart.setOption(option);
  } else {
    console.error('China JSON data is not loaded');
  }
}

// 交易额统计配置
const tradeChartOption = computed(() => ({
  grid: {
    top: '10%',
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['每秒', '每分钟', '每小时'],
    axisLabel: {
      color: '#fff'
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: '#fff',
      formatter: value => formatNumber(value) + '元'
    }
  },
  series: [{
    data: [
      Number(sellAndBuyList.value[0]),
      Number(sellAndBuyList.value[2]),
      Number(sellAndBuyList.value[4])
    ],
    type: 'bar',
    itemStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#00feff' },
        { offset: 1, color: '#027eff' }
      ])
    }
  }]
}));

// 辅助函数
const getTagType = (index) => {
  const types = ['success', 'warning', 'error'];
  return index < 3 ? types[index] : 'default';
};

const getTradeProgress = () => {
  const maxVolume = 10000; // 设置一个预期的最大交易量
  return Math.min((totalTradeVolume.value / maxVolume) * 100, 100);
};

const progressColor = '#2080f0'; // 使用单一颜色而不是渐变

const progressRailColor = 'rgba(255, 255, 255, 0.1)';

// 图标获取函数
const getPanelIcon = (index) => {
  const icons = [TimeOutline, StatsChartOutline, TrendingUpOutline];
  return icons[index];
};

const getRankingIcon = (index) => {
  const icons = [PodiumOutline, BusinessOutline];
  return icons[index];
};

</script>

<style scoped>
.dashboard {
  background: linear-gradient(135deg, #1a1c2a 0%, #0d1117 100%);
  min-height: 100vh;
  padding: 20px;
  animation: fadeIn 1s ease-in-out;
}

.header-card {
  margin-bottom: 20px;
  background: rgba(13, 17, 23, 0.7) !important;
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-wrapper {
  display: grid;
  grid-template-columns: 380px 1fr 380px;
  gap: 24px;
}

.info-card {
  margin-bottom: 20px;
  background: rgba(13, 17, 23, 0.7) !important;
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
}

.map-container {
  height: 500px;
  margin-bottom: 24px;
}

.map-content {
  width: 100%;
  height: 400px;
  border-radius: 8px;
  overflow: hidden;
  animation: zoomIn 0.5s ease-in-out;
}

.bottom-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.ranking-list {
  max-height: 400px;
  overflow-y: auto;
}

.ranking-item {
  padding: 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
  animation: slideIn 0.5s ease-in-out;
}

.ranking-item:hover {
  background: rgba(255, 255, 255, 0.05);
  transform: translateX(4px);
}

.rank-tag {
  min-width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ff7e5f, #feb47b);
  color: #fff;
  font-weight: bold;
}

.value-statistic {
  min-width: 120px;
  color: #fff;
  font-weight: bold;
}

.volume-stats {
  padding: 24px;
}

.total-volume {
  font-size: 32px;
  margin-bottom: 24px;
  color: #fff;
  font-weight: bold;
}

.progress-circle {
  width: 120px;
  height: 120px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes zoomIn {
  from {
    transform: scale(0.8);
  }
  to {
    transform: scale(1);
  }
}

@keyframes slideIn {
  from {
    transform: translateX(-20px);
  }
  to {
    transform: translateX(0);
  }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 深度选择器样式 */
:deep(.n-card) {
  background: rgba(13, 17, 23, 0.7) !important;
}

:deep(.n-card-header) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.n-statistic-value) {
  background: linear-gradient(45deg, #40a9ff, #69c0ff);
  -webkit-background-clip: text;
  color: transparent !important;
}

/* 响应式设计 */
@media (max-width: 1500px) {
  .content-wrapper {
    grid-template-columns: 1fr;
  }
  
  .bottom-charts {
    grid-template-columns: 1fr;
  }
}
</style>